package com.yun.zf.search.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.yun.zf.common.admin.model.community.CommunitySearchResMo;
import com.yun.zf.common.admin.model.house.HouseListMo;
import com.yun.zf.common.admin.model.search.CommunitySearchMo;
import com.yun.zf.common.admin.model.search.HouseSearchMo;
import com.yun.zf.common.annotation.LogPrint;
import com.yun.zf.common.app.dto.detail.CommunityNearByDto;
import com.yun.zf.common.esRes.CommunityResMo;
import com.yun.zf.common.esRes.HouseIndexResMo;
import com.yun.zf.common.esRes.HouseSearchDto;
import com.yun.zf.common.mapstruct.admin.HouseMapper;
import com.yun.zf.common.vo.Response;
import com.yun.zf.search.service.ESRestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "搜索")
@Slf4j
@RequestMapping("/search")
public class SearchController extends SearchBaseController {

    @Autowired
    private ESRestService esRestService;

    @PostMapping("/searchHouseBasic")
    @ApiOperation(value = "搜索房源信息")
    @ApiOperationSupport(order = 1)
    @LogPrint(description = "搜索房源信息")
    public Response<HouseSearchDto> searchHouse(@Validated @RequestBody HouseSearchMo houseSearchMo) {
        // 取当前城市
        houseSearchMo.setCityCode(String.valueOf(aCode));
        // 如果是地铁搜索，则先找到地铁线路下的所有小区
        if (StringUtils.isNotEmpty(houseSearchMo.getContext())||StringUtils.isNotEmpty(houseSearchMo.getSubway())|| StringUtils.isNotEmpty(houseSearchMo.getStations())) {
            CommunitySearchMo communitySearchMo = HouseMapper.INSTANCE.searchHouseToCommunity(houseSearchMo);
            // 获得地铁站下的小区ID
            Map<String, Object> community = esRestService.searchCommunitys(communitySearchMo);
            if (community == null) {
                return Response.success("未搜索到符合条件的数据");
            }
            //2、查询小区基本信息
            List<CommunityResMo> esResList = (List<CommunityResMo>) community.get("records");
            if (esResList.size() <= 0) {
                return Response.success("未查询到符合条件的小区信息");
            }
            StringBuilder sb = new StringBuilder();
            for (CommunityResMo res : esResList) {
                sb.append(res.getCid()).append(",");
            }
            // 将小区集合字符串赋值给搜索对象
            houseSearchMo.setCommunityId(sb.toString());
        }
        //1、 获取ES 中的房源id信息
        Map<String, Object> map = esRestService.searchHouseBasic(houseSearchMo);
        if (map == null) {
            return Response.success("未搜索到数据");
        }
        //2、 根据ID 查询列表信息
        List<HouseIndexResMo> sourceList = (List) map.get("records");
        List<Long> ids = new ArrayList<>();
        if (sourceList.size() <= 0) {
            return Response.success("未搜索到数据");
        }
        for (HouseIndexResMo hmap : sourceList) {
            ids.add(hmap.getHid());
        }
        Long proCode = sourceList.get(0).getProvinceCode();
        Long cityCode = sourceList.get(0).getCityCode();
        List<HouseListMo> houseListMos = esRestService.houseBasic(proCode, cityCode, ids);
        // 列表信息覆盖原data id 信息
        map.put("records", houseListMos);
        HouseSearchDto searchDto = new HouseSearchDto();
        searchDto.setCurrent(Integer.parseInt(map.get("current").toString()));
        searchDto.setRecords(houseListMos);
        searchDto.setTotalPage(Integer.parseInt(map.get("totalPage").toString()));
        searchDto.setTotal(Integer.parseInt(map.get("total").toString()));
        return Response.success(searchDto);
    }


    @PostMapping("/communitySuggestForHouse")
    @ApiOperation(value = "房源录入自动补全小区信息")
    @DynamicParameters(properties = {
            @DynamicParameter(name = "title",value = "小区名称",example = "金地",required = true)
    })
    public Response communitySuggestForHouse(@RequestBody Map<String,String>map) {
        String city = map.get("city");
        if (StringUtils.isNotBlank(city)){
           aCode= Long.parseLong(city);
        }
        List<Map<String, String>> suggests = esRestService.communitySuggestToHouse(map.get("title"), aCode);
        return Response.success(suggests);
    }

    /**
     * 搜索当前城市下的已经存在数据进行搜索
     */
    @PostMapping("/communitySuggest")
    @ApiOperation(value = "搜索框自动补全提示")
    @DynamicParameters(properties = {
            @DynamicParameter(name = "title",value = "小区名称",example = "金地",required = true)
    })
    public Response communitySuggest(String title) {
        List<Map<String, String>> suggests = esRestService.communitySuggest(title, aCode);
        return Response.success(suggests);
    }

    @PostMapping("/searchCommunitys")
    @ApiOperation(value = "小区搜索")
    public Response<CommunitySearchResMo> searchCommunitys(@RequestBody CommunitySearchMo communitySearchMo) {
        communitySearchMo.setCityCode(String.valueOf(aCode));
        // 1、 查询es中符合条件的小区Id信息
        Map<String, Object> community = esRestService.searchCommunitys(communitySearchMo);
        if (community == null) {
            return Response.success("未搜索到符合条件的数据");
        }
        //2、查询小区基本信息
        List<CommunityResMo> esResList = (List<CommunityResMo>) community.get("records");
        if (esResList.size() <= 0) {
            return Response.success("未查询到符合条件的小区信息");
        }
        List<Long> ids = new ArrayList<>();
        for (CommunityResMo res : esResList) {
            ids.add(res.getCid());
        }

        List<CommunityNearByDto> list = esRestService.getBasicCommunity(ids);
        CommunitySearchResMo searchResMo = new CommunitySearchResMo();
        searchResMo.setTotal(Integer.parseInt(community.get("total").toString()));
        searchResMo.setTotalPage(Integer.parseInt(community.get("totalPage").toString()));
        searchResMo.setCurPage(Integer.parseInt(community.get("current").toString()));
        searchResMo.setCommunitySearchListMos(list);
        return Response.success(searchResMo);
    }
}
